package com.chushouya.order.service.api.impl;

import com.alipay.api.domain.AlipayOpenMiniOrderDeliveryModifyModel;
import com.alipay.api.domain.GoodsInfoModifyDTO;

import com.alipay.api.domain.PriceInfoModifyDTO;
import com.alipay.api.domain.SendOrderContactInfoDTO;
import com.alipay.api.response.AlipayOpenMiniOrderDeliveryModifyResponse;
import com.chushouya.manager.service.common.AlipayClientCommonService;
import com.chushouya.order.constants.AlipayOrderChangedStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.entity.OrderProductEntity;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderProductRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.service.api.AlipayOpenMiniOrderDeliveryModifyService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AlipayOpenMiniOrderDeliveryModifyServiceImpl implements AlipayOpenMiniOrderDeliveryModifyService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;

    @Resource
    private AlipayClientCommonService alipayClientCommonService;

    /**
     * 获取订单信息
     * @param orderId
     */
    private OrderEntity getOrder(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw new RuntimeException("订单不存在");
        }
        return orderEntity;
    }

    /**
     * 订单额外信息
     * @param orderId
     */
    private OrderExtendEntity getOrderExtend(Long orderId) {
        OrderExtendEntity orderExtendEntity = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtendEntity)) {
            throw Ex.business("订单扩展信息不存在");
        }
        return orderExtendEntity;
    }

    /**
     * 获取产品列表
     * @param orderId
     */
    /**
     * 获取订单产品信息
     * @param orderId
     */
    private List<OrderProductEntity> getOrderProduct(Long orderId) {
        List<OrderProductEntity> orderProductEntities = orderProductRepository.getProductListByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderProductEntities)) {
            throw Ex.business("订单产品信息不存在");
        }
        return orderProductEntities;
    }


    @Override
    public AlipayOpenMiniOrderDeliveryModifyResponse confirmOrder(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        if (org.apache.logging.log4j.util.Strings.isEmpty(orderEntity.getOrderCenterNo())) {
            throw Ex.business("订单没有支付宝订单号，无法操作 订单号：{}", orderEntity.getOrderNo());
        }
        final String partnerOrderNo = orderEntity.getOrderCenterNo();
        final String orderNo = orderEntity.getOrderNo();
        final OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        final String openId = orderExtendEntity.getOpenId();
        AlipayOpenMiniOrderDeliveryModifyModel model = new AlipayOpenMiniOrderDeliveryModifyModel();
        model.setOrderId(partnerOrderNo);
        model.setOutOrderId(orderNo);
        model.setUserId(openId);
        model.setUserConfirmPrice(orderEntity.getCompletePrice().toString());
        model.setStatus(AlipayOrderChangedStatusEnum.USER_CONFIRMED.getValue());
        log.info("用户确认，订单号：{}", Jsons.toFormatJsonString(model));
        AlipayOpenMiniOrderDeliveryModifyResponse response = alipayClientCommonService.alipayOpenMiniOrderDeliveryModify(model);
        if (Objects.isNull(response) || !response.isSuccess()) {
            throw Ex.business(response.getSubMsg());
        }
        return response;
    }

    @Override
    public void confirmQuality(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        if (Strings.isEmpty(orderEntity.getOrderCenterNo())) {
            throw Ex.business("订单没有支付宝订单号，无法操作 订单号：{}", orderEntity.getOrderNo());
        }
        final BigDecimal completePrice = orderEntity.getCompletePrice();
        if (completePrice.compareTo(BigDecimal.ZERO) <= 0) {
            throw Ex.business("成交金额必须大于0，无法操作 订单号：{}", orderEntity.getOrderNo());
        }
        final String partnerOrderNo = orderEntity.getOrderCenterNo();
        final String orderNo = orderEntity.getOrderNo();
        final OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        final String openId = orderExtendEntity.getOpenId();
        AlipayOpenMiniOrderDeliveryModifyModel model = new AlipayOpenMiniOrderDeliveryModifyModel();
        model.setOrderId(partnerOrderNo);
        model.setOutOrderId(orderNo);
        model.setUserId(openId);
        model.setStatus(AlipayOrderChangedStatusEnum.MERCHANT_CONFIRMED.value());
        PriceInfoModifyDTO priceInfoModifyDTO = new PriceInfoModifyDTO();
        priceInfoModifyDTO.setRealOrderPrice(orderEntity.getCompletePrice().toString());
        model.setPriceInfo(priceInfoModifyDTO);

        alipayClientCommonService.alipayOpenMiniOrderDeliveryModify(model);
    }

    @Override
    public void confirmStopPay(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        final String partnerOrderNo = orderEntity.getOrderCenterNo();
        final String orderNo = orderEntity.getOrderNo();
        final OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        final String openId = orderExtendEntity.getOpenId();
        AlipayOpenMiniOrderDeliveryModifyModel model = new AlipayOpenMiniOrderDeliveryModifyModel();
        model.setOrderId(partnerOrderNo);
        model.setOutOrderId(orderNo);
        model.setUserId(openId);
        model.setStatus(AlipayOrderChangedStatusEnum.CLOSED.getValue());
        log.info("打款终止，订单号：{}", Jsons.toFormatJsonString(model));
        AlipayOpenMiniOrderDeliveryModifyResponse response = alipayClientCommonService.alipayOpenMiniOrderDeliveryModify(model);
        if (Objects.isNull(response) || !response.isSuccess()) {
            throw Ex.business(response.getSubMsg());
        }
    }

    @Override
    public void assignOrderDeliveryClerk(Long orderId) {
        OrderEntity orderEntity = getOrder(orderId);
        if (Strings.isEmpty(orderEntity.getOrderCenterNo())) {
            throw Ex.business("订单没有支付宝订单号，无法操作 订单号：{}", orderEntity.getOrderNo());
        }
        final String partnerOrderNo = orderEntity.getPartnerOrderNo();
        final String orderNo = orderEntity.getOrderNo();
        final OrderExtendEntity orderExtendEntity = getOrderExtend(orderId);
        final String clerkPhone = orderEntity.getClerkPhone();
        final String clerkName = orderEntity.getClerkName();
        final String openId = orderExtendEntity.getOpenId();
        AlipayOpenMiniOrderDeliveryModifyModel model = new AlipayOpenMiniOrderDeliveryModifyModel();
        SendOrderContactInfoDTO sendOrderContactInfoDTO = new SendOrderContactInfoDTO();
        sendOrderContactInfoDTO.setContactName(clerkName);
        sendOrderContactInfoDTO.setPhoneNumber(clerkPhone);
        model.setOrderId(partnerOrderNo);
        model.setOutOrderId(orderNo);
        model.setUserId(openId);
        model.setStatus(AlipayOrderChangedStatusEnum.ASSIGNED.value());
        model.setSendOrderContactInfo(sendOrderContactInfoDTO);
        alipayClientCommonService.alipayOpenMiniOrderDeliveryModify(model);
    }

    //    构建产品信息列表
    private List<GoodsInfoModifyDTO> buildGoodsInfoModifyDTOList(List<OrderProductEntity> orderProductEntities,BigDecimal qualityPrice) {
        List<GoodsInfoModifyDTO> goodsInfoModifyDTOList = Lists.newArrayList();
        for (OrderProductEntity orderProductEntity : orderProductEntities) {
            GoodsInfoModifyDTO goodsInfoModifyDTO = new GoodsInfoModifyDTO();
            goodsInfoModifyDTO.setOutItemId(orderProductEntity.getProductId().toString());
            goodsInfoModifyDTO.setOutSkuId(orderProductEntity.getProductId().toString());
            goodsInfoModifyDTO.setInspectPrice(qualityPrice.toString());
            goodsInfoModifyDTO.setRecycleStatus("VALID");
            goodsInfoModifyDTOList.add(goodsInfoModifyDTO);
        }
        return goodsInfoModifyDTOList;
    }
}
